package com.donkeyroll.mdtask;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.markdown4j.Markdown4jProcessor;

public class MdTask extends Task {

    private Vector<FileSet> filesets = new Vector<FileSet>();

    private String cssfile;

    private Markdown4jProcessor mdProcessor;

    public void execute() throws BuildException {
        if (filesets.size() == 0) {
            throw new BuildException(
                    "no fileset found! please make sure the fileset directory exists.");
        }
        // get css file
        String cssPath = getProject().getBaseDir().getAbsolutePath()
                + File.separator + cssfile;
        File cssFile = new File(cssPath);
        if (!cssFile.exists()) {
            throw new BuildException("css file \"" + cssPath
                    + "\" is not exist, abort!");
        }
        String cssString = "";
        try {
            FileReader fr = new FileReader(cssFile);
            BufferedReader br = new BufferedReader(fr);
            String strline;
            while ((strline = br.readLine()) != null) {
                cssString = cssString + System.getProperty("line.separator")
                        + strline;
            }
        } catch (FileNotFoundException e) {
            throw new BuildException(e);
        } catch (IOException e) {
            throw new BuildException(e);
        }
        mdProcessor = new Markdown4jProcessor();
        FileSet markdownRoot = filesets.get(0);
        DirectoryScanner ds = markdownRoot.getDirectoryScanner(getProject());
        String[] includedFiles = ds.getIncludedFiles();
        for (int i = 0; i < includedFiles.length; i++) {
            String filename = includedFiles[i].replace('\\', '/');
            if (!filename.endsWith(".md")) {
                log("this is not a markdown file!", Project.MSG_WARN);
                continue;
            }
            File mdFile = new File((markdownRoot.getDir(getProject())
                    .getAbsolutePath() + File.separator + filename));
            String newFileName = mdFile.getAbsolutePath();
            newFileName = newFileName.substring(0,
                    newFileName.lastIndexOf(".md"));
            newFileName = newFileName + ".html";
            File htmlFile = new File(newFileName);
            // delete if html file exists, because we are going to re-generate
            // it.
            if (htmlFile.exists()) {
                htmlFile.delete();
            }
            try {
                FileWriter fw = new FileWriter(htmlFile);
                String processed = mdProcessor.process(mdFile);
                fw.write("<html>");
                fw.write("<style type=\"text/css\">");
                fw.write(cssString);
                fw.write("</style>");
                fw.write(processed);
                fw.write("</html>");
                fw.flush();
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new BuildException(e);
            }
        }

    }

    public void addFileset(FileSet fileset) {
        filesets.add(fileset);
    }

    public void setCssfile(String cssfile) {
        this.cssfile = cssfile;
    }

}
